import QtQuick 2.0
import Sailfish.Silica 1.0
import "../config"

Label {
    id: clock
    font.pixelSize: Theme.fontSizeSmall
    color: textColor
    horizontalAlignment: Text.AlignHCenter
    leftPadding: 10
    rightPadding: 10
    topPadding: 4
    bottomPadding: 4

    property color backgroundColor: AppColor.themeMode.themeMerryCranesbill
    property color textColor: AppColor.themeMode.primaryColor
    property bool showSeconds: false
    readonly property int _baseInterval: showSeconds ? 1000 : 60000

    // 精准同步优化层
    layer.enabled: backgroundColor.a > 0
    layer.effect: ShaderEffect {
        property color bgColor: clock.backgroundColor
        fragmentShader: "
        varying highp vec2 qt_TexCoord0;
        uniform lowp sampler2D source;
        uniform lowp vec4 bgColor;
        void main() {
            lowp vec4 pix = texture2D(source, qt_TexCoord0);
            gl_FragColor = mix(bgColor, pix, pix.a);
        }"
    }

    // 智能时间同步器
    Timer {
        id: syncTimer
        triggeredOnStart: true
        running: Qt.application.active && visible
        onTriggered: {
            const now = Date.now();
            const nextInterval = _baseInterval;

            // 精准同步算法（仅分钟模式）
            if (!showSeconds) {
                const remain = _baseInterval - (now % _baseInterval);
                nextInterval = remain > 100 ? remain : _baseInterval;
            }

            // 动态调整触发周期
            interval = nextInterval;
            updateTime(now);

            // 优化后续触发（避免重复计算）
            if (!showSeconds) interval = _baseInterval;
        }
    }

    // 高性能时间更新
    function updateTime(timestamp) {
        const date = new Date(timestamp || Date.now())
        text = Qt.formatTime(date, timeFormat(date))
    }

    // 动态格式生成器
    function timeFormat(date) {
        const hasAP = Qt.locale().timeFormat(Locale.ShortFormat).indexOf("AP") !== -1
        const format

        if (showSeconds) {
            format = hasAP ? "hh:mm:ss AP" : "HH:mm:ss"
        } else {
            // 优化分钟同步时的格式生成
            format = hasAP ? "hh:mm AP" : "HH:mm"
        }

        return format
    }

    // 生命周期优化
    Component.onCompleted: updateTime()
    Component.onDestruction: syncTimer.stop()

    // 响应式格式更新
    onShowSecondsChanged: {
        if (syncTimer.running) {
            syncTimer.restart()
        }
    }

    // 内存优化绑定
    Connections {
        target: Qt.application
        onActiveChanged: if (active) updateTime()
    }
}
